<template>
	<view class="bgbox po_rel" style="`height:${navigationinfo.windowHeight}px`">
		<un-navbar titleText="选择转发" bgColor="rgba(0,0,0,0)">
			<template #content>
				<view class="po_abs dxclass flex align_center f_s32">
					<view style="color: #39C7C1;" @click="duoxuanfun()">
						{{!state.duoxuan?'多选':state.system_codelist.length?'发送':'取消'}}
					</view>
				</view>
			</template>
		</un-navbar>
		<view id="scrollview">
			<scroll-view scroll-y="true" @scrolltolower="loadMore" class="wi_100 flex"
				:style="`height:${navigationinfo.windowHeight-navigationinfo.allHeight}px`">
				<view class="flex1 flex flex_column"
					:style="`min-height:${navigationinfo.windowHeight-navigationinfo.allHeight}px`">
					<view class="pa20">
						<view class="flex align_center search_box bg_white po_rel">
							<view class="iconfont i-fdj te_black9 ma_lr30"></view>
							<input class="flex1 f_s28" placeholder="请输入关键词搜索" v-model="state.name" confirm-type="search"
								maxlength="30" @confirm="searchName" />
							<view v-if="state.searchtype&&state.name" class="ma_right30"
								@click="state.searchtype=false,state.name=''">
								返回
							</view>
							<view v-if="state.searchtype&&state.name" class="searchboxs bg_white po_abs">

								<view v-if="state.searchlist.length">
									<view class="pa24" v-for="(item,index) in state.searchlist"
										@click="!state.duoxuan?forwardfun(item,3):toggleItem(item,3)">
										<view class="flex align_center">
											<view
												style="margin-top: 14upx;margin-right: 16upx;width: 34upx;height: 34upx;"
												v-if="state.duoxuan">
												<view class="multipleclass"
													v-show="state.duoxuan&&state.system_codelist?.findIndex(selectedItem => item.contact_user_system_code  === selectedItem.targetId)===-1">
												</view>
												<image class="multipleclass2"
													v-show="state.duoxuan&&state.system_codelist?.length&&state.system_codelist?.findIndex(selectedItem =>  item.contact_user_system_code  === selectedItem.targetId)!=-1"
													src="../../static/image/chat/chatduogous.png">
												</image>
											</view>

											<image class="ma_right30 topuserimgbox" :src="item.contact_user_avatar">
											</image>
											<view class="flex1 chatinfo pa_tb30">
												<view class="f_s34">
													{{item.contact_user_name_cn}}
												</view>
											</view>
										</view>
									</view>
								</view>
								<view v-if="!state.searchlist.length">
									<view class="flex justify_center ma_top100">
										搜不到好友信息
									</view>
								</view>
							</view>
						</view>
					</view>

					<view class="flex pa24 align_center bg_white ma_bottom24"
						v-if="state.duoxuan&&state.system_codelist.length">
						<view class="ma_right20" v-for="(item,index) in state.system_codelist">
							<view class="po_rel">
								<image class="topuserimgbox" :src="item.avatar"></image>
								<image class="topclose po_abs" src="../../static/image/chat/closess.png"
									@click="state.system_codelist.splice(index,1)"></image>
							</view>
						</view>
						<view>
							已选{{state.system_codelist.length}}人
						</view>
					</view>

					<view class="pa_lr24 flex flex_column">
						<view class="bg_white bo_radius22 pa_lr24 pa_top30 pa_bottom40" v-if="state.zjzflist.length">
							<view class="f_s32 ma_bottom30">最近转发</view>
							<scroll-view scroll-x="true" @scrolltolower="loadMore" class="wi_100 flex topscroll nowraps"
								scroll-with-animation>
								<view class="di_inbl ma_lr20" v-for="(item,index) in state.zjzflist"
									@click.stop="!state.duoxuan?forwardfun(item,1):toggleItem(item,1)"
									:class="state.duoxuan?'pa_top10':''">
									<view class="flex align_center flex_column po_rel">
										<view class="multipleclasss po_abs"
											v-show="state.duoxuan&&state.system_codelist?.findIndex(selectedItem => item.share_contact_system_code  === selectedItem.targetId)===-1">
										</view>
										<image class="multipleclass2s po_abs"
											v-show="state.duoxuan&&state.system_codelist?.length&&state.system_codelist?.findIndex(selectedItem =>  item.share_contact_system_code  === selectedItem.targetId)!=-1"
											src="../../static/image/chat/chatduogous.png">
										</image>


										<image class="topuserimgbox flex align_center justify_center"
											:src="(item.share_contact_avatar||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'">
										</image>
										<view class="ma_top10 f_s26 topnames te_center ellipsis">
											{{item.share_contact_name_cn}}
										</view>
									</view>
								</view>

							</scroll-view>
						</view>

						<view class="bg_white bo_radius22 pa_lr24 pa_top30 pa_bottom40 ma_top20 flex flex_column"
							v-if="!state.searchtype&&!state.name">
							<view class="f_s32">最近聊天</view>
							<view v-for="(item,index) in store.state.conversationList" :key="index">
								<view class="chatlist flex align_center"
									v-if="store.state.myinfo.system_code!=item.targetId"
									@click.stop="!state.duoxuan?forwardfun(item,2):toggleItem(item,2)">
									<view style="margin-top: 20upx;margin-right: 16upx;width: 34upx;height: 34upx;"
										v-if="state.duoxuan">
										<!-- 
										<view class="multipleclass" v-if="state.duoxuan"></view>
										<image class="multipleclass2" v-if="state.duoxuan"
											src="../../static/image/chat/chatduogous.png"></image> -->


										<view class="multipleclass"
											v-show="state.duoxuan&&state.system_codelist?.findIndex(selectedItem => item.targetId  === selectedItem.targetId)===-1">
										</view>
										<image class="multipleclass2"
											v-show="state.duoxuan&&state.system_codelist?.length&&state.system_codelist?.findIndex(selectedItem =>  item.targetId  === selectedItem.targetId)!=-1"
											src="../../static/image/chat/chatduogous.png">
										</image>
									</view>



									<image class="ma_right30"
										:src="(store.state.friendinfo[item.targetId].avatar||'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png')+'?x-oss-process=image/resize,p_30'">
									</image>
									<view class="flex1 chatinfo pa_tb50">
										<view class="f_s34">
											{{store.state.friendinfo[item.targetId].remark_name}}
										</view>
									</view>
								</view>
							</view>
						</view>

					</view>


				</view>
			</scroll-view>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { showToast, getnavigationinfo } from '@/utils/utils'
	import { onLoad, onShow, onUnload, onReady } from '@dcloudio/uni-app'
	import { ref, reactive, getCurrentInstance, watch } from 'vue'
	import { friend_info } from '@/api/addressbook'
	import { recently_share, user_recently_share_contactquery } from '@/api/chat'
	import { user_contact_query } from '@/api/addressbook'

	import { useStore } from 'vuex'
	const store = useStore()
	const instance = getCurrentInstance(); // 获取组件实例

	const navigationinfo = ref<any>(uni.getStorageSync('navigationinfo'))

	getnavigationinfo()

	onReady(async () => {

	})


	const searchName = () => {
		if (!state.name) {
			return
		}
		let datas = {

			"pagination": {
				"page": 1,
				"size": 50
			},
			"filter": {
				"user_id": 0,
				"deleted": true,
				"blocked": true,
				"remark_name": state.name
			},
			"sorter": {
				"additionalProp1": "asc",
				"additionalProp2": "asc",
				"additionalProp3": "asc"
			}

		}
		console.log('datasdatas', datas)
		user_contact_query(datas).then(res => {
			state.searchtype = true
			state.searchlist = res.data.items
			console.log(res.data.items)
		})
	}




	watch(() => state.name, (newValue, oldValue) => {
		if (!newValue) {
			state.searchtype = false
		}
	}, {
		deep: true, immediate: true
	});








	user_recently_share_contactquery({
		"pagination": {
			"page": 1,
			"size": 10
		},
		"filter": {

		},
		"sorter": {
		}
	}).then(res => {
		console.log('最近转发的人', res)
		state.zjzflist = res.data
	})

	onLoad((e) => {
		state.forward = uni.getStorageSync('forward')

		if (state.forward[0].messageType == 4) {//如果是媒体文件

			// "remote": "https://bucket7-a-3.ronghub.com/WlVaD1xTCVZaAFkPUGF7CgMDCgoOAAkJBQAKCnV5CggEAQsJAAEPCwECCg83Mjg4.jpg?e=1752912277&token=CddrKW5AbOMQaDRwc3ReDNvo3-sL_SO1fSUBKV3H:2Y9Bp_AIRxvsv1qSO8Uj1OaoljQ=",
			//"local": "file:///data/user/0/jin.buff/files/24tn-8BzX0xGZ4fJEdO3XQ_1737356147000/image/local/22.jpg",
			console.log(state.forward)
		}
		console.log('state.forward', state.forward)
		uni.setStorageSync('forward', '')

	})




	user_contact_query



	const forwardfun = (item, type) => {
		console.log('转发的人', item)
		console.log('转发type是', type)
		//targetId
		uni.showModal({
			title: '提示',
			content: '确认消息发送给' + (type == 1 ? item.share_contact_name_cn : type == 2 ? store.state.friendinfo[item.targetId]?.remark_name : item.contact_user_name_cn),
			success: function (res) {
				if (res.confirm) {
					state.system_codelist.push({ targetId: (type == 1 ? item.share_contact_system_code : type == 2 ? item.targetId : item.contact_user_system_code) })
					console.log('state.system_codelist', state.system_codelist)
					state.system_codelist.map((item, index) => {
						sunmit(item.targetId)
						if (index == state.system_codelist.length - 1) {
							setTimeout(() => {
								uni.setStorageSync('forwardtype', true)
								uni.navigateBack()
							}, 500)
						}

					})
					recently_shares()
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}

	const sunmit = async (targetId) => {
		if (state.forward[0].messageType == 2) {//文本消息

			let text = state.forward[0].text
			let callback = {
				onMessageSaved: (res) => {
					console.log('onMessageSavedonMessageSaved', res)

					//...
				},
				onMessageSent: (res) => {
					if (store.state.targetId == targetId) {
						if (res.code == 0) {
							//store.dispatch('getMessages', state.userinfo.targetId,0)
							let datas = {
								num: 0,
								type: 1,
								targetId: targetId,

							}

							store.dispatch('getConversations', datas)

						}
					} else {
						let datas = {
							num: 0,
							targetId: null,
							type: 2
						}
						store.dispatch('getConversations', datas)
					}

				}

			};


			console.log('转发文本消息', state.forward[0])
			let message = {
				text,
				conversationType: 1,
				targetId,
				extra: '',
				content: text,
				messageType: 2,
			}

			console.log('message', message)
			let code = await store.state.engine.sendMessage(message, callback);
		} else if (state.forward[0].messageType == 4) {//媒体消息
			let listener = {
				onMediaMessageSaved: (res) => {
					console.log('onMediaMessageSaved', res)
					//...
				},
				onMediaMessageSending: (res) => {
					console.log('onMediaMessageSending', res)
					//...
				},
				onSendingMediaMessageCanceled: (res) => {
					console.log('onSendingMediaMessageCanceled', res)
					//...
				},
				onMediaMessageSent: (res) => {
					console.log('onMediaMessageSent', res)

					if (store.state.targetId == targetId) {
						if (res.code == 0) {
							//store.dispatch('getMessages', state.userinfo.targetId,0)
							let datas = {
								num: 0,
								type: 1,
								targetId: targetId,

							}

							store.dispatch('getConversations', datas)

						}
					} else {
						let datas = {
							num: 0,
							targetId: null,
							type: 2
						}
						store.dispatch('getConversations', datas)
					}


					//...
				}

			};


			let message = {
				local: state.forward[0].localurl,
				targetId,
				conversationType: 1,
				messageType: 4

			}

			console.log('state.forward[0].localurl', state.forward[0].localurl)
			let code = await store.state.engine.sendMediaMessage(message, listener);
		} else if (state.forward[0].messageType == 1) {//自定义消息  
			
			let callback = {
				onMessageSaved: (res) => {
					console.log('onMessageSavedonMessageSaved', res)
					//...
				},
				onMessageSent: (res) => {
					console.log('onMessageSentonMessageSent', res)
					
					if (store.state.targetId == targetId) {
						if (res.code == 0) {
							//store.dispatch('getMessages', state.userinfo.targetId,0)
							let datas = {
								num: 0,
								type: 1,
								targetId: targetId,
					
							}
					
							store.dispatch('getConversations', datas)
					
						}
					} else {
						let datas = {
							num: 0,
							targetId: null,
							type: 2
						}
						store.dispatch('getConversations', datas)
					}
			
					//...
				}
			
			};
			
			
			let fields = {
				img: state.forward[0].fields.img,
				name:state.forward[0].fields.name,
				system_code: state.forward[0].fields.system_code,
				targetId: state.forward[0].fields.targetId,
			}

			let message = await store.state.engine.createCustomMessage(
				1,
				targetId,
				null,
				1,
				'chat_diy',
				fields
			);



			let code = await store.state.engine.sendMessage(message, callback);



		}




	}


	const recently_shares = () => {
		state.system_codelist.map((item, index) => {
			console.log('11111111', {
				system_code: item.targetId,
				share_type: 'person'
			})
			recently_share({
				system_code: item.targetId,
				share_type: 'person'
			}).then(res => {
				if (index == state.system_codelist.length - 1) {
					state.system_codelist = []
				}
			})
		})


	}


	const toggleItem = (item, type) => {
		console.log('多选选择的是--', item)
		console.log('多选类型是11111--', type)
		let indexs = null

		if (type == 1) {
			indexs = state.system_codelist.findIndex(selectedItem => selectedItem.targetId === item.share_contact_system_code);

		} else if (type == 2) {
			indexs = state.system_codelist.findIndex(selectedItem => selectedItem.targetId === item.targetId);
		} else {
			indexs = state.system_codelist.findIndex(selectedItem => selectedItem.targetId === item.contact_user_system_code);
		}
		if (indexs === -1) {
			if (state.system_codelist.length < 5) {
				state.system_codelist.push({ targetId: item.targetId || item.share_contact_system_code || item.contact_user_system_code, avatar: (type == 1 ? item.share_contact_avatar : type == 2 ? (store.state.friendinfo[item.targetId].avatar || 'https://vpay-static.oss-cn-shenzhen.aliyuncs.com/static/unmanned/images/main/morentouxiang.png') : item.contact_user_avatar) + '?x-oss-process=image/resize,p_30' });
			} else {
				uni.showToast({
					title: '最多只能选5个人',
					icon: 'none',
					duration: 2000
				});
			}
		} else {
			state.system_codelist.splice(indexs, 1);
		}
	}


	const state = reactive({
		searchlist: [],
		searchtype: false,
		name: null,
		zjzflist: [],
		system_codelist: [],
		forward: null,
		targetId: null,
		scrollviewheight: null,
		tipsshow: false,
		duoxuan: false
	})

	const duoxuanfun = () => {
		if (!state.duoxuan) {
			state.duoxuan = true
		} else if (!state.system_codelist.length) {
			state.duoxuan = false
		} else if (state.system_codelist.length) {
			uni.showModal({
				title: '提示',
				content: '确认消息发送给多人？',
				success: function (res) {
					if (res.confirm) {
						state.system_codelist.map((item, index) => {
							sunmit(item.targetId)
							if (index == state.system_codelist.length - 1) {
								setTimeout(() => {
									uni.setStorageSync('forwardtype', true)
									uni.navigateBack()
								}, 500)
							}

						})
						recently_shares()
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		}

	}
</script>
<style>

</style>

<style scoped lang="scss">
	$ztcolor: #39C7C1;

	.zttecolor {
		color: $ztcolor;
	}

	.ztbgcolor {
		background-color: $ztcolor;
	}

	.bgbox {
		width: 100vw;
		height: 100vh;


	}

	.search_box {
		height: 72upx;
		border-radius: 36upx;
	}

	.topscroll {
		height: 160upx;

	}


	.topnames {
		width: 110upx;
	}

	.chatlist {
		image {
			width: 94upx;
			height: 94upx;
			border-radius: 30upx;
		}

		.chatinfo {
			border-bottom: 1upx solid #F6F6F6;
		}
	}

	.topuserimgbox {
		width: 94upx;
		height: 94upx;
		border-radius: 30upx;

	}

	.topclose {
		width: 30upx;
		height: 30upx;
		top: -4upx;
		right: 4upx;
		z-index: 1;
	}

	.dxclass {
		right: 30upx;
	}

	.multipleclass {
		width: 30upx;
		height: 30upx;
		border-radius: 50%;
		border: 2upx solid #D0D0D0;
	}

	.multipleclass2 {
		width: 34upx !important;
		height: 34upx !important;
	}

	.multipleclasss {
		width: 30upx;
		height: 30upx;
		border-radius: 50%;
		border: 2upx solid #D0D0D0;
		background: #fff;
		right: -4upx;
		top: -4upx;
		z-index: 1;
	}

	.multipleclass2s {
		width: 34upx !important;
		height: 34upx !important;
		right: -4upx;
		top: -4upx;
		z-index: 1;
	}

	.searchboxs {
		width: 100%;
		height: 750upx;
		overflow-y: auto;
		left: 0;
		top: 80upx;
		z-index: 50;

	}
</style>